//list directories
//
// lsd(1) lists all directories in the current directory, or in the directories
// specified on the command line. By default it does not display directories
// that begin with a . such as .hg.
package main

import (
	"os"
	path "path/filepath"
	"fmt"
	"flag"
	"log"
)

var (
	ShowDotFiles = flag.Bool(".", false, "list hidden files as well")
	Invert       = flag.Bool("v", false,
		"invert: show only files that are not directories")
)

func lsd(dir string, join, hidedot bool) {
	f, err := os.Open(dir)
	if err != nil {
		log.Println(err)
		return
	}

	for {
		stats, err := f.Readdir(100)
		if err != nil {
			log.Println(err)
		}
		if len(stats) == 0 {
			return
		}

		for _, stat := range stats {
			show := stat.IsDirectory()
			if *Invert {
				show = !show
			}
			if !show {
				continue
			}
			if hidedot && stat.Name[0] == '.' {
				continue
			}

			name := stat.Name
			if join {
				name = path.Join(dir, name)
			}
			fmt.Println(name)
		}
	}
}

//Usage: %name %flags dirnames*
func main() {
	log.SetFlags(0)
	flag.Parse()
	hide := !*ShowDotFiles

	dirs := flag.Args()
	if len(dirs) == 0 {
		pwd, err := os.Getwd()
		if err != nil {
			log.Fatalln(err)
		}
		lsd(pwd, false, hide)
		return
	}

	for _, dir := range dirs {
		lsd(dir, true, hide)
	}
}
